<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片的懒加载实现方式2</title>
    <style>
        img {
            display: block;
        }
    </style>
</head>

<body>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">

    <script>

        // 获取所有img的DOM节点
        let images = document.querySelectorAll('img')

        // 懒加载函数，entire为监听元素的类数组
        function lazyLoad(entires) {
            entires.forEach(item => {
                // 是否显示了？
                if (item.isIntersecting) {
                    // 获取图片目标
                    const image = item.target
                    // 获取data-src的值
                    const data_src = image.getAttribute('data-src')
                    // 将data-src赋给src属性
                    image.setAttribute('src', data_src)
                    // 关闭监听，提升性能
                    observer.unobserve(image)
                    console.log('触发');
                }

            })

        }
        // 创建IntersectionObserver实例，接收一个回调函数
        let observer = new IntersectionObserver(lazyLoad)

        // 监听每个图片元素
        images.forEach(item => {
            observer.observe(item)
        });

    </script>
</body>

</html>